package zhoufu.sz.sanxiao_check.ui;

import android.app.Activity;
import android.content.Intent;
import android.gesture.Gesture;
import android.gesture.GestureOverlayView;
import android.graphics.Bitmap;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import zhoufu.sz.sanxiao_check.R;


public class GestureViewActivity extends AppCompatActivity
        implements GestureOverlayView.OnGestureListener,
        GestureOverlayView.OnGesturePerformedListener, OnClickListener
{

    GestureOverlayView mGestureOverlayView;
    private boolean isGesture = false;//是否画过
    private AsyncTask<Object, Object, Object> asyncTask;
    public static final String RESULT_DATA = "data";


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gesture);
        init();
    }


    public static void startActivityForResult(Activity activity, int requestCode)
    {
        activity.startActivityForResult(new Intent(activity, GestureViewActivity.class),
                requestCode);
    }

    //@Override
    //public boolean onCreateOptionsMenu(Menu menu)
    //{
    //    menu.add(0, 0, 0, "保存")
    //            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    //    menu.add(0, 1, 1, "清除")
    //            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    //    menu.add(0, 2, 2, "取消")
    //            .setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    //    return true;
    //}
    //
    //@Override
    //public boolean onOptionsItemSelected(MenuItem item)
    //{
    //    switch (item.getItemId())
    //    {
    //        case 0:// 保存
    //            save();
    //            break;
    //        case 1:// 清除
    //            clear();
    //            break;
    //        case 2:// 取消
    //            cancle();
    //            break;
    //    }
    //    return super.onOptionsItemSelected(item);
    //}

    @Override
    public void onClick(View v)
    {

        switch (v.getId())
        {
            case R.id.btn_save:
                try
                {
                    save();
                } catch (Exception e)
                {
                    Toast.makeText(this, "保存签名失败， 请重试", Toast.LENGTH_SHORT);
                    return;
                }
                break;
            case R.id.btn_clear:
                clear();
                break;
            case R.id.btn_cancel:
                cancle();
                break;
        }
    }

    private void init()
    {
        mGestureOverlayView = (GestureOverlayView) findViewById(R.id.gestureOverlayView);
        // 设置手势正在绘制师的颜色
        mGestureOverlayView.setUncertainGestureColor(getResources().getColor(
                android.R.color.black));
        // 设置手势已经完成的颜色
        mGestureOverlayView.setGestureColor(getResources().getColor(
                android.R.color.black));
        mGestureOverlayView.setGestureStrokeWidth(8.0f);
        // 支持多笔绘画
        mGestureOverlayView
                .setGestureStrokeType(GestureOverlayView.GESTURE_STROKE_TYPE_MULTIPLE);
        mGestureOverlayView.addOnGestureListener(this);
        mGestureOverlayView.setFadeOffset(3600000);
        mGestureOverlayView.addOnGesturePerformedListener(this);
        mGestureOverlayView.setDrawingCacheEnabled(true);
        // =========
        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_clear).setOnClickListener(this);
        findViewById(R.id.btn_cancel).setOnClickListener(this);
    }

    private void save()
    {
        if ( mGestureOverlayView != null )
        {
            if ( !isGesture )
            {
                Toast.makeText(this, "请签名后在保存", Toast.LENGTH_SHORT);
                return;
            }
            Bitmap bitmap = mGestureOverlayView.getDrawingCache();
            if ( bitmap == null )
            {
                return;
            }
            asyncTask = new AsyncTask<Object, Object, Object>()
            {
                @Override
                protected Object doInBackground(Object... params)
                {
                    try
                    {
                        Bitmap bitmap = (Bitmap) params[0];

                        File file = new File(getExternalCacheDir(),
                                System.currentTimeMillis() + "sign.png");


                        FileOutputStream fos = new FileOutputStream(file);
                        if ( bitmap == null || bitmap.isRecycled() )
                        {
                            finish();
                            return null;
                        }
                        bitmap.compress(Bitmap.CompressFormat.PNG, 100, fos);
                        fos.flush();
                        fos.close();
                        bitmap.recycle();

                        Intent intent = new Intent();
                        intent.putExtra(RESULT_DATA, file.getPath());
                        setResult(RESULT_OK, intent);
                    } catch (FileNotFoundException e)
                    {
                        e.printStackTrace();
                    } catch (IOException e)
                    {
                        e.printStackTrace();
                    } catch (Exception e)
                    {
                    }
                    return null;
                }

                protected void onPostExecute(Object result)
                {
                    if ( mGestureOverlayView != null )
                    {
                        clear();
                    }
                    finish();
                }
            }.execute(bitmap);
        }
    }

    private void clear()
    {
        isGesture = false;
        // 设置消失间隔时间，毫秒
        mGestureOverlayView.setFadeOffset(50);
        mGestureOverlayView.clear(true);
        // 设置消失间隔时间，毫秒
        mGestureOverlayView.setFadeOffset(1000 * 3600);
        mGestureOverlayView.destroyDrawingCache();
    }

    private void cancle()
    {
        mGestureOverlayView.clear(true);
        mGestureOverlayView.destroyDrawingCache();
        finish();
    }

    /***************
     * OnGestureListener Start
     ******************/

    @Override
    public void onGestureStarted(GestureOverlayView overlay, MotionEvent event)
    {
        // TODO Auto-generated method stub
        // Log.e("", "onGestureStarted");
    }

    @Override
    public void onGesture(GestureOverlayView overlay, MotionEvent event)
    {
        // TODO Auto-generated method stub
        // Log.e("", "onGesture");
        isGesture = true;
    }

    @Override
    public void onGestureEnded(GestureOverlayView overlay, MotionEvent event)
    {
        // TODO Auto-generated method stub
        // Log.e("", "onGestureEnded");
    }

    @Override
    public void onGestureCancelled(GestureOverlayView overlay, MotionEvent event)
    {
        // TODO Auto-generated method stub
        // Log.e("", "onGestureCancelled");
    }

    /*************** OnGestureListener End ******************/

    /********
     * GesturePerformedListener
     *******************/
    @Override
    public void onGesturePerformed(GestureOverlayView overlay, Gesture gesture)
    {
        // Log.e("", "onGesturePerformed手势绘画完成");
    }

    @Override
    protected void onDestroy()
    {
        if ( asyncTask != null && !asyncTask.isCancelled() )
        {
            asyncTask.cancel(true);
        }
        super.onDestroy();
    }
}
